package org.example.binding;

import org.dom4j.Element;
import org.dom4j.Node;
import org.example.Configuration;
import org.example.builder.StaticSqlSource;
import org.example.mapping.MappedStatement;
import org.example.mapping.SqlCommandType;

import java.util.List;

public class XMLStatementBuilder {


    private final String namespace;

    private final  Element element;


    private final Configuration configuration;



    public XMLStatementBuilder(String namespace, Element element,Configuration configuration) {
        this.namespace = namespace;
        this.element = element;
        this.configuration = configuration;
    }


    public void parse() {
        String name = element.getName();
        String id = element.attributeValue("id");
        String resultType = element.attributeValue("resultType");
        Class<?> resultTypeClazz;
        try {
             resultTypeClazz = Class.forName(resultType);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("解析返回值类型失败");
        }
        List<Node> content = element.content();
        if(content == null && content.isEmpty()) {
            throw new RuntimeException("没有任何SQL语句");
        }
        StringBuilder builder = new StringBuilder();
        for (Node node : content) {
            String text = node.getText();
            builder.append(text);
        }
        String sql =  builder.toString();
        StaticSqlSource source = new StaticSqlSource(sql, null);

        MappedStatement statement = new MappedStatement();
        statement.setId(id);
        statement.setResultType(resultTypeClazz);
        statement.setSqlSource(source);
        statement.setConfiguration(configuration);
        SqlCommandType type = SqlCommandType.getInstance(name);
        statement.setSqlCommandType(type);


        String nameStatement = namespace + "." + id;
        statement.setId(nameStatement);
        configuration.addMappedStatement(statement);

        System.out.println(content);

    }







}
